const { spawn } = require('child_process');
const path = require('path');

// 配置
const config = {
  instances: 3, // 实例数量
  basePort: 3000, // 基础端口
  electronPath: path.join(__dirname, '../node_modules/.bin/electron'),
  mainPath: path.join(__dirname, '../electron/main.js'),
  nextPath: path.join(__dirname, '../node_modules/.bin/next')
};

// 存储所有的进程
const processes = [];

// 清理函數
function cleanup() {
  console.log('\正在关闭所有的实例...');
  processes.forEach(process => {
    if (!process.killed) {
      process.kill('SIGTERM');
    }
  });
  process.exit(0);
}

// 监听退出信号
process.on('SIGINT', cleanup);
process.on('SIGTERM', cleanup);

// 等待服务器启动
function waitForServer(url, maxAttempts = 30) {
  return new Promise((resolve, reject) => {
    const http = require('http');
    let attempts = 0;
    
    const checkServer = () => {
      attempts++;
      const req = http.get(url, (res) => {
        if (res.statusCode === 200) {
          console.log(`服务器已经准备就绪: ${url}`);
          resolve();
        } else {
          if (attempts < maxAttempts) {
            setTimeout(checkServer, 1000);
          } else {
            reject(new Error(`服务器启动超时了: ${url}`));
          }
        }
      });
      
      req.on('error', () => {
        if (attempts < maxAttempts) {
          setTimeout(checkServer, 1000);
        } else {
          reject(new Error(`无法连接到服务器: ${url}`));
        }
      });
      
      req.setTimeout(5000, () => {
        req.destroy();
        if (attempts < maxAttempts) {
          setTimeout(checkServer, 1000);
        } else {
          reject(new Error(`服务器连接超时: ${url}`));
        }
      });
    };
    
    checkServer();
  });
}

// 启动多个实例
async function startMultipleInstances() {
  console.log(`正在启动 ${config.instances} 个 Electron 实例...`);
  
  // 首先启动Next.js关闭服务器
  console.log('启动 Next.js 服务器...');
  const nextProcess = spawn(config.nextPath, ['dev', '-p', config.basePort], {
    cwd: path.join(__dirname, '..'),
    stdio: 'pipe',
    detached: false
  });
  
  processes.push(nextProcess);
  
  // 等待服务器启动
  try {
    await waitForServer(`http://localhost:${config.basePort}`);
  } catch (error) {
    console.error('服务器启动失败:', error.message);
    cleanup();
    return;
  }
  // sleep一会，确保启动完全完成
  await new Promise(resolve => setTimeout(resolve, 2000));
  
  // 循环启动
  for (let i = 0; i < config.instances; i++) {
    const instanceId = i + 1;
    
    // 设置环境变量
    const env = {
      ...process.env,
      NODE_ENV: 'development',
      ELECTRON_INSTANCE_ID: instanceId.toString()
    };
    
    console.log(`启动 Electron 实例 ${instanceId}`);
    
    // 启动ELectron进程
    const electronProcess = spawn(config.electronPath, [config.mainPath], {
      env,
      stdio: 'pipe',
      detached: false
    });
    
    // 监听进程事件
    electronProcess.on('error', (error) => {
      console.error(`实例 ${instanceId} 启动失败:`, error);
    });
    
    electronProcess.on('exit', (code) => {
      console.log(`实例 ${instanceId} 已退出，code: ${code}`);
    });
    
    processes.push(electronProcess);
    
    // 延迟启动下一个实例
    if (i < config.instances - 1) {
      await new Promise(resolve => setTimeout(resolve, 1000));
    }
  }
  
  console.log(`\n已启动 ${config.instances} 个 Electron 实例。按 Ctrl+C 关闭所有实例`);
  
  nextProcess.stdout.on('data', (data) => {
    console.log(`[Next.js] ${data.toString().trim()}`);
  });
  
  nextProcess.stderr.on('data', (data) => {
    console.error(`[Next.js Error] ${data.toString().trim()}`);
  });
}

startMultipleInstances().catch(console.error); 